package com.company.nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @description:
 * @author: zgw
 * @create: 2021-03-12 15:53
 **/
public class GroupChatClient {

    private Selector selector;

    private SocketChannel socketChannel;

    private String userName;

    public GroupChatClient(){
        try {
            this.selector = Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",GroupChatServer.PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            userName = socketChannel.getLocalAddress().toString();
            System.out.println(userName.replace("/","")+" is ok~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //发送消息到服务端
    private void sendMsg(String msg){
        msg = userName + "说："+msg;
        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取服务端发送过来的消息
    private void readMsg(){
        try {
            //其相应的通道已准备好进行
            int count = selector.select();
            if (count>0){
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    //判断是读就绪事件
                    if (selectionKey.isReadable()){
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        channel.read(byteBuffer);
                        byte[] bytes = byteBuffer.array();
                        System.out.println(new String(bytes));
                    }
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        GroupChatClient client = new GroupChatClient();
        new Thread(()->{
            while (true){
                client.readMsg();
                try {
                    Thread.sleep(3000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

        //主线程发送消息到服务器
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String msg = scanner.nextLine();
            client.sendMsg(msg);
        }
    }

}
